﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net;
using System.Net.Mail;
using MSBDATAModel;
using System.Security.Cryptography;

/// <summary>
/// Summary description for MyTools
/// </summary>
public class Util
{
    private static string PassMaHoa = "bimat";
    public Util()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public static void ClearControls(Control Parent)
    {

        if (Parent is TextBox)

        { (Parent as TextBox).Text = string.Empty; }

        else
        {

            foreach (Control c in Parent.Controls)

                ClearControls(c);
        }

    }
    /// <summary>
    /// http://orb-of-knowledge.blogspot.com/2009/08/extremely-fast-luhn-function-for-c.html
    /// Validates a credit card number using the standard Luhn/mod10
    /// validation algorithm.
    /// </summary>
    /// <param name="cardNumber">Card number, with or without
    ///        punctuation</param>
    /// <returns>True if card number appears valid, false if not
    /// </returns>
    public static bool IsCreditCardValid(string cardNumber)
    {
        int[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 };
        int checksum = 0;
        char[] chars = cardNumber.ToCharArray();
        for (int i = chars.Length - 1; i > -1; i--)
        {
            int j = ((int)chars[i]) - 48;
            checksum += j;
            if (((i - chars.Length) % 2) == 0)
                checksum += DELTAS[j];
        }

        return ((checksum % 10) == 0);
    }

    public static void SendMailToCustomer(string email, string username)
    {
        MSBDATAEntities entities = new MSBDATAEntities();

        string _mailServer = "smtp.gmail.com";
        int _mailPort = 587; // Work well, 465 Timeout

        var matches = from c in entities.C_CAU_HINH
                      where c.Ma == 1
                      select c;

        C_CAU_HINH ch = matches.First();

        string _user = ch.Email;
        string _pass = ch.PassMail;

        string _mailFrom = ch.Email;
        string _mailTo = email;
        MailMessage mailMessage = new MailMessage();
        SmtpClient mailClient = new SmtpClient(_mailServer, _mailPort);
        mailClient.Timeout = 15000;
        mailClient.Credentials = new NetworkCredential(_user, _pass);
        mailClient.EnableSsl = true;

        mailMessage.IsBodyHtml = true;
        mailMessage.From = new MailAddress(_mailFrom);
        mailMessage.Subject = "Kích hoạt tài khoản";

        string href = ch.LinkKichHoat + Util.EncryptString(username);

        mailMessage.Body = "<h3>Bạn đã tạo tài khoản web tại ngân hàng MSB, click vào link sau để kích hoạt:</h3>" +
                            "<a href=" + href + ">"
                            + href
                            + "</a> <br/>";

        mailMessage.To.Add(_mailTo);
        try
        {
            mailClient.Send(mailMessage);
        }
        catch (Exception)
        {

        }
    }


    public static string EncryptString(string Message)
    {
        string Passphrase = Util.PassMaHoa;
        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

        // Buoc 1: Bam chuoi su dung MD5

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

        // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        // Step 3. Cai dat bo ma hoa
        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;

        // Step 4. Convert chuoi (Message) thanh dang byte[]
        byte[] DataToEncrypt = UTF8.GetBytes(Message);

        // Step 5. Ma hoa chuoi
        try
        {
            ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
            Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
        }
        finally
        {
            // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }

        // Step 6. Tra ve chuoi da ma hoa bang thuat toan Base64
        return Convert.ToBase64String(Results);
    }

    public static string DecryptString(string Message)
    {
        string Passphrase = Util.PassMaHoa;

        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

        // Step 1. Bam chuoi su dung MD5

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

        // Step 2. Tao doi tuong TripleDESCryptoServiceProvider moi
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        // Step 3. Cai dat bo giai ma
        TDESAlgorithm.Key = TDESKey;
        TDESAlgorithm.Mode = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;

        // Step 4. Convert chuoi (Message) thanh dang byte[]
        byte[] DataToDecrypt = Convert.FromBase64String(Message);

        // Step 5. Bat dau giai ma chuoi
        try
        {
            ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
            Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
        }
        finally
        {
            // Xoa moi thong tin ve Triple DES va HashProvider de dam bao an toan
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }

        // Step 6. Tra ve ket qua bang dinh dang UTF8
        return UTF8.GetString(Results);
    }

    public static string SinhSoTheThanhToanTrucTuyen()
    {
        MSBDATAEntities entities = new MSBDATAEntities();
        try
        {
            SO_THE_THANH_TOAN s = null;
            foreach (SO_THE_THANH_TOAN st in entities.SO_THE_THANH_TOAN)
            {
                if (st.DaSuDung == false)
                {
                    var matches = from sttt in entities.SO_THE_THANH_TOAN
                                  where sttt.SoThe == st.SoThe
                                  select sttt;

                    s = matches.First();
                    s.DaSuDung = true;
                    break;
                }
            }
            if (s != null && entities.SaveChanges() > 0)
                return s.SoThe;
            return null;
        }
        catch (Exception)
        {
            return null;
        }
    }
    public static string SinhSoTheATM(TAI_KHOAN_WEB tk)
    {
        return DateTime.Now.ToString("ssyyyyMMssddhhmm");
    }
    public static string SinhSoTaiKhoanNganHang()
    {
        return "MSB" + DateTime.Now.ToString("yyssddMMhhmmss");
    }
    public static TAI_KHOAN_NGAN_HANG TaoTaiKhoanNganHang(TAI_KHOAN_WEB tk)
    {
        MSBDATAEntities entities = new MSBDATAEntities();

        TAI_KHOAN_NGAN_HANG tknh = TAI_KHOAN_NGAN_HANG.CreateTAI_KHOAN_NGAN_HANG(Util.SinhSoTaiKhoanNganHang());

        tknh.SoTien = 0;
        tknh.TAI_KHOAN_WEB = entities.TAI_KHOAN_WEB.First(t => t.TenDangNhap == tk.TenDangNhap);
        tknh.C_TIEN_TE = entities.C_TIEN_TE.First(tt => tt.MaTienTe == "VND");

        entities.AddToTAI_KHOAN_NGAN_HANG(tknh);
        if (entities.SaveChanges() > 0)
            return tknh;
        return null;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="CardId"></param>
    /// <param name="CardType"></param>
    /// <param name="CardSecureNumber"></param>
    /// <param name="CardHolder"></param>
    /// <param name="ValidFromDate"></param>
    /// <param name="ValidToDate"></param>
    /// <returns>
    /// -1: Invalid SID
    /// 0 : Card valid
    /// 1 : Card ID is not valid for this bank
    /// 2 : Card Type is not valid (Visa/Master)
    /// 3 : Customer Name not valid
    /// 4 : Secure Number of the Credit card is not valid
    /// 5 : Input Date of user for the credit card are not valid
    /// 6 : Out of valid date from now
    /// 7 : Card is stolen
    /// </returns>
    public static int CardValid1(string CardId, string CardType, string CardSecureNumber, string CardHolder, DateTime ValidFromDate, DateTime ValidToDate)
    {
        MSBDATAEntities entities = new MSBDATAEntities();
        try
        {
            C_CAU_HINH ch = entities.C_CAU_HINH.First(c => c.Ma == 1);
            return 2;
        }
        catch (Exception) {
            return -1;
        }
        
    }

    public static int CardValid2(string CardId, string CardType, string CardSecureNumber, string CardHolder)
    {
        MSBDATAEntities entities = new MSBDATAEntities();
        try
        {
            C_CAU_HINH ch = entities.C_CAU_HINH.First(c => c.Ma == 1);
            return 2;
        }
        catch (Exception)
        {
            return -1;
        }
    }
    
    public static int CardValid3(string CardId)//, string CardType, string CardHolder)
    {
        MSBDATAEntities entities = new MSBDATAEntities();
        try
        {
            C_CAU_HINH ch = entities.C_CAU_HINH.First(c => c.Ma == 1);
            //string sid = (string)WebserviceInvoker.WSInvoker.CallWebService(ch.LinkECCardWS, "EMVServices", "Authenticate", new Object[]
            //{ 
            //    ch.MaGiaoDich,
            //    ch.PassECCardWS
            //});
            //string sid = (string)WebserviceInvoker.WSInvoker.CallWebService("http://www.is.fit.hcmuns.edu.vn/EMV_Service/EMVServices.asmx", "EMVServices", "Authenticate", new Object[]
            //{ 
            //    "MSB",
            //    "803P8s93i112v83UG44X"
            //});

            EMVServices.EMVServices service = new EMVServices.EMVServices();
            string sid = service.Authenticate("MSB", "803P8s93i112v83UG44X");
            
            if (sid == null || sid == "Fail")
                return -1;

            try
            {
                SO_THE_THANH_TOAN soThe = entities.SO_THE_THANH_TOAN.First(s => s.SoThe == CardId);
                int result = (int)WebserviceInvoker.WSInvoker.CallWebService(ch.LinkECCardWS, "EMVServices", "CardValid3", new Object[]
                            { 
                                sid,
                                CardId,
                                soThe.Loai,
                                ch.MaGiaoDich
                            });

                return result;
            }
            catch (Exception)
            {
                return -1;
            }
        }
        catch (Exception)
        {
            return -1;
        }
    }


    public static string LayMaTienTeMacDinh()
    {
        return "VND";
    }
    public static int LayMaTyGiaMoiNhat(string MaTienTe)
    {
        MSBDATAEntities entities = new MSBDATAEntities();
        try {
            List<C_TY_GIA> dsTyGia = (from t in entities.C_TY_GIA
                                     where t.MaTienTe == MaTienTe
                                     select t).ToList();
            return dsTyGia[dsTyGia.Count - 1].MaTyGia;
        }
        catch (Exception) {
            return 1;// VND
        }
    }
}